﻿using System;
using System.Web.DynamicData;
using System.Web.UI.WebControls;

namespace NotAClue.Web.DynamicData
{
    public static class CascadeHierarchicalExtensions
    {
        /// <summary>
        /// Sets the initial value.
        /// </summary>
        /// <param name="listControl">The list control.</param>
        /// <param name="fkColumn">The foreign key column.</param>
        /// <param name="foreignkey">The foreign key.</param>
        public static void SetInitialValue(this ListControl listControl, MetaForeignKeyColumn fkColumn, String foreignkey)
        {
            var parentTable = fkColumn.ParentTable;
            var parentQuery = parentTable.GetQuery();

            var item = parentQuery.Provider.Execute(
                parentQuery.BuildSingleItemQuery(
                    parentTable,
                    foreignkey.Split(new char[] { ',' })));

            listControl.Items.Clear();
            listControl.Items.Add(new ListItem()
            {
                Text = parentTable.GetDisplayString(item),
                Value = foreignkey
            });
            listControl.SelectedValue = foreignkey;
        }

        /// <summary>
        /// Gets the GetPropertyValue from a string value.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="table">The table.</param>
        /// <param name="value">The value.</param>
        /// <returns>The named properties value.</returns>
        public static Object GetTypeFromString(this Type type, MetaTable table, String value)
        {
            var query = table.GetQuery();
            // Get primary key column
            var pkColumn = table.GetPrimaryKeyColumn();

            var objValue = query.GetFirstOrDefaultUsingColumn(pkColumn, value);
            return objValue;
        }
    }
}
